<template>
  <div class="page-container">
    <h1 class="page-title">🧭 导航中</h1>
    
    <!-- 地图 -->
    <div class="card">
      <div id="map" class="map-container"></div>
    </div>
    
    <!-- 当前状态 -->
    <div class="card" v-if="session">
      <h3>{{ session.poi?.name || '散步中' }}</h3>
      <p>已行走: {{ formatDistance(totalDistance) }}</p>
      <p>用时: {{ formatDuration(elapsedTime) }}</p>
    </div>
    
    <!-- 景点介绍 -->
    <div class="card" v-if="poiIntroduction">
      <h3>📖 景点介绍</h3>
      <p>{{ poiIntroduction }}</p>
      <button class="btn btn-secondary" @click="playTTS" :disabled="playingTTS">
        {{ playingTTS ? '播放中...' : '🔊 播放语音' }}
      </button>
    </div>
    
    <!-- 音乐播放器 -->
    <div class="card music-player" v-if="currentMusic">
      <div class="player-info">
        <h4>🎵 {{ currentMusic.name || '背景音乐' }}</h4>
        <p>{{ currentMusic.mood || '轻松愉快' }}</p>
      </div>
      <div class="player-controls">
        <button @click="toggleMusic">
          <img :src="isPlaying ? '/images/pause.png' : '/images/play.png'" alt="播放">
        </button>
        <button @click="saveMusic">
          <img src="/images/share.png" alt="保存">
        </button>
      </div>
    </div>
    
    <!-- 到达选择 -->
    <div class="card arrival-choice" v-if="arrivedAtPoi">
      <h3>🎉 已到达 {{ session.poi?.name }}</h3>
      <p>接下来您想？</p>
      <div class="choice-buttons">
        <button class="btn btn-primary" @click="continueWalking">继续逛下一个景点</button>
        <button class="btn btn-secondary" @click="goHome">我要回家</button>
      </div>
    </div>
    
    <!-- 控制按钮 -->
    <div style="text-align: center; margin-top: 20px;">
      <button class="btn btn-secondary" @click="endSession">结束散步</button>
    </div>
  </div>
</template>

<script>
import { watchLocation, clearWatch, calculateDistance, formatDistance } from '../utils/location'
import { sessionApi, poiApi, routeApi } from '../utils/api'

export default {
  name: 'Navigation',
  data() {
    return {
      session: null,
      currentLocation: null,
      watchId: null,
      map: null,
      userMarker: null,
      totalDistance: 0,
      startTime: null,
      elapsedTime: 0,
      timer: null,
      poiIntroduction: null,
      currentMusic: null,
      isPlaying: false,
      playingTTS: false,
      arrivedAtPoi: false,
      audioContext: null
    }
  },
  mounted() {
    this.initSession()
    this.startTimer()
  },
  beforeUnmount() {
    this.cleanup()
  },
  methods: {
    formatDistance,
    
    formatDuration(seconds) {
      const mins = Math.floor(seconds / 60)
      const secs = seconds % 60
      return `${mins}分${secs}秒`
    },
    
    initSession() {
      const sessionData = localStorage.getItem('currentSession')
      if (sessionData) {
        this.session = JSON.parse(sessionData)
        this.startTime = Date.now()
        this.startLocationWatch()
        this.initMap()
      } else {
        this.$router.push('/route-planner')
      }
    },
    
    initMap() {
      // 使用Leaflet初始化地图
      if (this.session?.route?.start_location) {
        const { latitude, longitude } = this.session.route.start_location
        this.map = L.map('map').setView([latitude, longitude], 15)
        
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
          attribution: '© OpenStreetMap'
        }).addTo(this.map)
        
        // 添加用户标记
        this.userMarker = L.marker([latitude, longitude]).addTo(this.map)
        
        // 添加目标POI标记
        if (this.session.poi?.location) {
          L.marker([
            this.session.poi.location.latitude,
            this.session.poi.location.longitude
          ]).addTo(this.map)
            .bindPopup(this.session.poi.name)
        }
        
        // 绘制路径
        if (this.session.route?.waypoints) {
          const points = this.session.route.waypoints.map(wp => [wp.latitude, wp.longitude])
          L.polyline(points, { color: '#4CAF50', weight: 4 }).addTo(this.map)
        }
      }
    },
    
    startLocationWatch() {
      let lastLocation = null
      
      this.watchId = watchLocation(
        location => {
          this.currentLocation = location
          
          // 更新地图
          if (this.userMarker) {
            this.userMarker.setLatLng([location.latitude, location.longitude])
            this.map.panTo([location.latitude, location.longitude])
          }
          
          // 计算距离
          if (lastLocation) {
            const dist = calculateDistance(
              lastLocation.latitude, lastLocation.longitude,
              location.latitude, location.longitude
            )
            this.totalDistance += dist
          }
          lastLocation = location
          
          // 检测是否到达POI
          this.checkArrival(location)
          
          // 更新后端
          if (this.session?.sessionId) {
            sessionApi.updateLocation(this.session.sessionId, location)
          }
        },
        error => {
          console.error('位置监听错误:', error)
        }
      )
    },
    
    checkArrival(location) {
      if (!this.session?.poi?.location || this.arrivedAtPoi) return
      
      const distance = calculateDistance(
        location.latitude, location.longitude,
        this.session.poi.location.latitude,
        this.session.poi.location.longitude
      )
      
      if (distance < 30) { // 30米内视为到达
        this.arrivedAtPoi = true
        this.loadPOIIntroduction()
        this.playArrivalSound()
      }
    },
    
    async loadPOIIntroduction() {
      if (!this.session?.poi?.id) return
      
      try {
        const response = await poiApi.getIntroduction(this.session.poi.id)
        this.poiIntroduction = response.introduction || response.data?.introduction
      } catch (error) {
        console.error('获取景点介绍失败:', error)
      }
    },
    
    playArrivalSound() {
      // 播放提示音
      const audio = new Audio('/sounds/arrival.mp3')
      audio.play().catch(() => {})
    },
    
    playTTS() {
      this.playingTTS = true
      // 使用Web Speech API
      if ('speechSynthesis' in window && this.poiIntroduction) {
        const utterance = new SpeechSynthesisUtterance(this.poiIntroduction)
        utterance.lang = 'zh-CN'
        utterance.onend = () => { this.playingTTS = false }
        speechSynthesis.speak(utterance)
      } else {
        this.playingTTS = false
      }
    },
    
    toggleMusic() {
      this.isPlaying = !this.isPlaying
      // 实际音乐播放逻辑
    },
    
    saveMusic() {
      if (this.currentMusic?.id) {
        // 保存音乐到库
        alert('音乐已保存到音乐库')
      }
    },
    
    async continueWalking() {
      this.arrivedAtPoi = false
      
      try {
        const response = await routeApi.replanRoute(
          this.currentLocation,
          'next',
          null
        )
        
        // 更新会话
        this.session.route = response.data || response
        localStorage.setItem('currentSession', JSON.stringify(this.session))
        
        // 重新绘制路径
        this.initMap()
      } catch (error) {
        console.error('重新规划路径失败:', error)
        alert('重新规划路径失败')
      }
    },
    
    async goHome() {
      const homeLocation = JSON.parse(localStorage.getItem('homeLocation'))
      
      if (!homeLocation) {
        alert('请先设置家的位置')
        return
      }
      
      try {
        const response = await routeApi.replanRoute(
          this.currentLocation,
          'home',
          homeLocation
        )
        
        this.session.route = response.data || response
        this.arrivedAtPoi = false
        localStorage.setItem('currentSession', JSON.stringify(this.session))
        
        this.initMap()
      } catch (error) {
        console.error('规划回家路径失败:', error)
      }
    },
    
    async endSession() {
      if (confirm('确定要结束散步吗？')) {
        try {
          if (this.session?.sessionId) {
            await sessionApi.end(this.session.sessionId)
          }
          localStorage.removeItem('currentSession')
          this.$router.push('/footprint')
        } catch (error) {
          console.error('结束会话失败:', error)
          this.$router.push('/footprint')
        }
      }
    },
    
    startTimer() {
      this.timer = setInterval(() => {
        if (this.startTime) {
          this.elapsedTime = Math.floor((Date.now() - this.startTime) / 1000)
        }
      }, 1000)
    },
    
    cleanup() {
      if (this.watchId) {
        clearWatch(this.watchId)
      }
      if (this.timer) {
        clearInterval(this.timer)
      }
    }
  }
}
</script>

<style scoped>
.music-player {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.player-controls {
  display: flex;
  gap: 8px;
}

.player-controls button {
  width: 40px;
  height: 40px;
  border: none;
  border-radius: 50%;
  background: #f0f0f0;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.player-controls button img {
  width: 20px;
  height: 20px;
}

.arrival-choice {
  text-align: center;
}

.choice-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 16px;
}
</style>
